<!-- 任务管理页面 -->
<template>
	<view class="task-container page-container">
		<view class="status_bar" />
		<!-- 导航栏 -->
		<view class="task-header">
			<view class="menu-button" @click="onMenuClick">
				<u-icon name="list" size="24" color="var(--text-color)"></u-icon>
			</view>
			<view class="header-content">
				<text class="header-title">{{ currentGroup ? `${currentList.title} - ${currentGroup.name}` : '任务' }}</text>
				<text class="header-count" v-if="currentGroup">{{ todoTasks.length ? `(${doneTasks.length}/${allTasks.length})` : '' }}</text>
			</view>
			<view class="header-right">
				<u-icon name="search" size="24" color="var(--text-color)" @click="showSearch"></u-icon>
				<u-icon name="more-dot-fill" size="24" color="var(--text-color)" style="margin-left: 15px;" @click="showMore"></u-icon>
			</view>
		</view>
		
		<!-- 主要内容区 -->
		<scroll-view class="task-content" scroll-y>
			<template v-if="currentGroup && allTasks.length > 0">
				<view class="task-sections-container">
					<!-- 待办任务 -->
					<view class="task-section" v-if="todoTasks.length > 0">
						<view class="task-section-header" @click="toggleSection('todo')">
							<view class="task-section-left">
								<view class="task-section-indicator todo-indicator"></view>
								<text class="task-section-title">待办</text>
								<text class="task-section-count">{{ todoTasks.length }}</text>
							</view>
							<view class="task-section-toggle">
								<u-icon :name="todoCollapsed ? 'arrow-down' : 'arrow-up'" size="18" color="#999"></u-icon>
							</view>
						</view>
						<view class="task-list-wrapper" :class="{'collapsed': todoCollapsed}">
							<view class="task-list">
								<TaskItem 
									v-for="task in todoTasks" 
									:key="task.id" 
									:task="task"
									@click="openTaskDetail"
									class="task-item-wrapper"
								/>
							</view>
						</view>
					</view>
					
					<!-- 进行中任务 -->
					<view class="task-section" v-if="doingTasks.length > 0">
						<view class="task-section-header" @click="toggleSection('doing')">
							<view class="task-section-left">
								<view class="task-section-indicator doing-indicator"></view>
								<text class="task-section-title">进行中</text>
								<text class="task-section-count">{{ doingTasks.length }}</text>
							</view>
							<view class="task-section-toggle">
								<u-icon :name="doingCollapsed ? 'arrow-down' : 'arrow-up'" size="18" color="#999"></u-icon>
							</view>
						</view>
						<view class="task-list-wrapper" :class="{'collapsed': doingCollapsed}">
							<view class="task-list">
								<TaskItem 
									v-for="task in doingTasks" 
									:key="task.id" 
									:task="task"
									@click="openTaskDetail"
									class="task-item-wrapper"
								/>
							</view>
						</view>
					</view>
					
					<!-- 已完成任务 -->
					<view class="task-section" v-if="doneTasks.length > 0">
						<view class="task-section-header" @click="toggleSection('done')">
							<view class="task-section-left">
								<view class="task-section-indicator done-indicator"></view>
								<text class="task-section-title">已完成</text>
								<text class="task-section-count">{{ doneTasks.length }}</text>
							</view>
							<view class="task-section-toggle">
								<u-icon :name="doneCollapsed ? 'arrow-down' : 'arrow-up'" size="18" color="#999"></u-icon>
							</view>
						</view>
						<view class="task-list-wrapper" :class="{'collapsed': doneCollapsed}">
							<view class="task-list">
								<TaskItem 
									v-for="task in doneTasks" 
									:key="task.id" 
									:task="task"
									@click="openTaskDetail"
									class="task-item-wrapper"
								/>
							</view>
						</view>
					</view>
				</view>
			</template>
			
			<!-- 空状态 -->
			<view class="task-empty" v-else>
				<view class="empty-container">
					<image class="empty-image" src="/static/empty-task.svg" mode="aspectFit"></image>
					<text class="empty-text">暂无任务数据</text>
					<view class="empty-tips">
						<text>点击下方"+"按钮添加新任务</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 添加按钮 -->
		<view class="add-button" @click="showAddTask">
			<u-icon name="plus" color="#fff" size="24"></u-icon>
		</view>
		
		<!-- 清单抽屉 -->
		<ListDrawer :visible="drawerVisible" @close="onDrawerClose" />
		
		<!-- 任务详情组件 -->
		<TaskDetail 
			:show="showTaskDetail" 
			:task="currentTask || {}"
			@close="hideTaskDetail"
			@edit="editTask"
			@toggle-status="toggleTaskStatus"
			@timer="startTaskTimer"
		/>
		
		<!-- 任务操作菜单 -->
		<TaskActions 
			:show="showTaskActionsMenu" 
			:task="currentActionTask || {}"
			@close="hideTaskActions"
			@edit="editTask"
			@toggle-status="toggleTaskStatus"
			@timer="startTaskTimer"
			@delete="deleteTask"
		/>
		
		<!-- 任务表单模态框 -->
		<TaskModal
			:visible="showTaskModal"
			:taskData="currentEditTask"
			:isEdit="isEditMode"
			:groupId="currentGroup ? currentGroup.id : ''"
			:closeOnClickMask="false"
			@cancel="hideTaskModal"
			@submit="submitTaskForm"
		/>
		
		<!-- 使用uView的提示组件 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import ListDrawer from '@/components/ListDrawer.vue';
import TaskItem from '@/components/TaskItem.vue';
import TaskDetail from '@/components/task/TaskDetail.vue';
import TaskActions from '@/components/task/TaskActions.vue';
import TaskModal from '@/components/task/TaskModal.vue';
import { themeManager } from '@/utils/theme';

export default {
	components: {
		ListDrawer,
		TaskItem,
		TaskDetail,
		TaskActions,
		TaskModal
	},
	data() {
		return {
			drawerVisible: false,
			todoTasks: [],
			doingTasks: [],
			doneTasks: [],
			allTasks: [],
			currentList: null,
			currentGroup: null,
			// 任务详情相关
			showTaskDetail: false,
			currentTask: null,
			// 任务操作相关
			showTaskActionsMenu: false,
			currentActionTask: null,
			// 任务表单相关
			showTaskModal: false,
			currentEditTask: null,
			isEditMode: false,
			// 区块折叠状态
			todoCollapsed: false,
			doingCollapsed: false,
			doneCollapsed: false,
		}
	},
	onShow() {
		// 每次页面显示时更新数据
		this.updateCurrentData();
	},
	onLoad() {
		// 初始化应用数据
		this.initData();
		
		// 监听主题变化
		uni.$on('themeChange', this.handleThemeChange);
	},
	onUnload() {
		// 移除监听
		uni.$off('themeChange', this.handleThemeChange);
	},
	mounted() {
		// 初始化
	},
	updated() {
		// 数据更新
	},
	watch: {
		// 移除监听
	},
	methods: {
		// 显示优雅的提示
		showToast(message, type = 'info') {
			if (this.$refs.uToast) {
				this.$refs.uToast.show({
					title: message,
					type: type,
					icon: type === 'success' ? 'checkmark-circle' : (type === 'error' ? 'close-circle' : 'info-circle')
				});
			}
		},
		
		// 初始化数据
		async initData() {
			try {
				// 触发Vuex初始化
				if (this.$store && this.$store.dispatch) {
					await this.$store.dispatch('initAppData');
				} else {
					console.error('Store not initialized correctly');
				}
				
				// 更新页面数据
				this.updateCurrentData();
			} catch (error) {
				console.error('初始化数据失败:', error);
			}
		},
		
		// 更新当前数据
		updateCurrentData() {
			try {
				const store = this.$store;
				if (!store) {
					console.error('Store not available');
					return;
				}
				
				// 获取当前清单
				if (store.state && store.state.lists) {
					const currentListId = store.state.lists.currentListId;
					if (currentListId && store.getters && store.getters['lists/getCurrentList']) {
						this.currentList = store.getters['lists/getCurrentList'];
					}
					
					// 获取当前分组
					const currentGroupId = store.state.lists.currentGroupId;
					if (currentGroupId) {
						if (store.getters['lists/getCurrentGroup']) {
							this.currentGroup = store.getters['lists/getCurrentGroup'];
						}
						
						// 获取当前分组的任务
						if (store.getters['tasks/getTasksByGroup']) {
							this.allTasks = store.getters['tasks/getTasksByGroup'](currentGroupId) || [];
						}
						
						if (store.getters['tasks/getTodoTasksByGroup']) {
							this.todoTasks = store.getters['tasks/getTodoTasksByGroup'](currentGroupId) || [];
						}
						
						if (store.getters['tasks/getDoingTasksByGroup']) {
							this.doingTasks = store.getters['tasks/getDoingTasksByGroup'](currentGroupId) || [];
						}
						
						if (store.getters['tasks/getDoneTasksByGroup']) {
							this.doneTasks = store.getters['tasks/getDoneTasksByGroup'](currentGroupId) || [];
						}
					}
				}
				
				// 获取抽屉状态
				if (store.state && store.state.drawerVisible !== undefined) {
					this.drawerVisible = store.state.drawerVisible;
				}
			} catch (error) {
				console.error('更新数据失败:', error);
			}
		},
		
		// 主题变化处理
		handleThemeChange(data) {
			// 主题变化时更新页面样式
			console.log('任务页面接收到主题变化:', data.theme);
		},
		
		// 点击菜单按钮
		onMenuClick() {
			// 切换抽屉状态
			this.drawerVisible = !this.drawerVisible;
			
			// 通知Vuex状态变化（如果可用）
			try {
				if (this.$store && this.$store.dispatch) {
					this.$store.dispatch('toggleDrawer');
				}
			} catch (error) {
				console.error('切换抽屉状态失败:', error);
			}
		},
		
		// 打开任务详情
		openTaskDetail(task) {
			if (!task || !task.id) {
				this.showToast('任务数据无效', 'error');
				return;
			}
			
			try {
				// 创建深拷贝以避免引用问题
				this.currentTask = JSON.parse(JSON.stringify(task));
				this.showTaskDetail = true;
			} catch (error) {
				console.error('打开任务详情失败:', error);
				this.showToast('操作失败', 'error');
			}
		},
		
		// 隐藏任务详情
		hideTaskDetail() {
			this.showTaskDetail = false;
			// 延迟清空数据，确保动画完成
			setTimeout(() => {
				this.currentTask = null;
			}, 300);
		},
		
		// 显示任务操作菜单
		openTaskActions(task) {
			if (!task || !task.id) {
				this.showToast('任务数据无效', 'error');
				return;
			}
			
			try {
				// 创建深拷贝以避免引用问题
				this.currentActionTask = JSON.parse(JSON.stringify(task));
				this.showTaskActionsMenu = true;
			} catch (error) {
				console.error('显示任务操作菜单失败:', error);
				this.showToast('操作失败', 'error');
			}
		},
		
		// 隐藏任务操作菜单
		hideTaskActions() {
			this.showTaskActionsMenu = false;
			// 延迟清空数据，确保动画完成
			setTimeout(() => {
				this.currentActionTask = null;
			}, 300);
		},
		
		// 显示搜索
		showSearch() {
			this.showToast('搜索功能待实现', 'info');
		},
		
		// 显示更多选项
		showMore() {
			// 如果有当前任务，显示任务操作菜单
			if (this.currentTask) {
				this.openTaskActions(this.currentTask);
			} else {
				this.showToast('请先选择一个任务', 'info');
			}
		},
		
		// 显示添加任务
		showAddTask() {
			if (!this.currentGroup) {
				this.showToast('请先选择一个分组', 'warning');
				return;
			}
			
			this.isEditMode = false;
			this.currentEditTask = null;
			this.showTaskModal = true;
		},
		
		// 编辑任务
		editTask(task) {
			if (!task || !task.id) {
				this.showToast('任务数据无效', 'error');
				return;
			}
			
			this.isEditMode = true;
			this.currentEditTask = task;
			this.showTaskModal = true;
		},
		
		// 隐藏任务表单模态框
		hideTaskModal() {
			this.showTaskModal = false;
			// 延迟清空数据，确保动画完成
			setTimeout(() => {
				this.currentEditTask = null;
				this.isEditMode = false;
			}, 300);
		},
		
		// 提交任务表单
		submitTaskForm(taskData) {
			try {
				if (!this.$store || !this.$store.dispatch) {
					throw new Error('Store not available');
				}
				
				if (!taskData || (this.isEditMode && !taskData.id)) {
					throw new Error('任务数据无效');
				}
				
				// 先关闭模态框
				this.hideTaskModal();
				
				if (this.isEditMode) {
					// 编辑模式
					this.$store.dispatch('tasks/updateTask', taskData);
					this.showToast('任务已更新', 'success');
				} else {
					// 新建模式
					this.$store.dispatch('tasks/createTask', taskData);
					this.showToast('任务已创建', 'success');
				}
				
				// 更新数据
				this.updateCurrentData();
			} catch (error) {
				console.error('保存任务失败:', error);
				this.showToast('保存任务失败', 'error');
			}
		},
		
		// 切换任务状态
		toggleTaskStatus(taskId) {
			try {
				if (!taskId || !this.$store || !this.$store.dispatch) {
					throw new Error('无效的参数或Store不可用');
				}
				
				this.$store.dispatch('tasks/toggleTaskStatus', taskId);
				this.showToast('任务状态已更新', 'success');
				
				// 更新数据
				this.updateCurrentData();
			} catch (error) {
				console.error('切换任务状态失败:', error);
				this.showToast('操作失败', 'error');
			}
		},
		
		// 删除任务
		deleteTask(taskId) {
			try {
				if (!taskId || !this.$store || !this.$store.dispatch) {
					throw new Error('无效的参数或Store不可用');
				}
				
				this.$store.dispatch('tasks/deleteTask', taskId);
				this.showToast('任务已删除', 'success');
				
				// 更新数据
				this.updateCurrentData();
			} catch (error) {
				console.error('删除任务失败:', error);
				this.showToast('删除失败', 'error');
			}
		},
		
		// 开始任务计时
		startTaskTimer(taskId) {
			this.showToast('计时功能待实现', 'info');
		},
		
		// 关闭抽屉
		onDrawerClose() {
			this.drawerVisible = false;
			
			// 通知Vuex状态变化（如果可用）
			try {
				if (this.$store && this.$store.dispatch) {
					this.$store.dispatch('closeDrawer');
				}
			} catch (error) {
				console.error('关闭抽屉失败:', error);
			}
			
			// 抽屉关闭后更新数据
			this.updateCurrentData();
		},
		
		// 切换区块折叠状态
		toggleSection(section) {
			// 添加延迟以确保动画更流畅
			setTimeout(() => {
				switch(section) {
					case 'todo':
						this.todoCollapsed = !this.todoCollapsed;
						break;
					case 'doing':
						this.doingCollapsed = !this.doingCollapsed;
						break;
					case 'done':
						this.doneCollapsed = !this.doneCollapsed;
						break;
				}
			}, 10);
		}
	}
}
</script>

<style lang="scss" scoped>
.task-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: var(--background-color);
	width: 100%;
	overflow-x: hidden;
	box-sizing: border-box;
}

.task-header {
	display: flex;
	align-items: center;
	padding: 15px;
	border-bottom: 1px solid rgba(0, 0, 0, 0.05);
	width: 100%;
	box-sizing: border-box;
}

.menu-button {
	padding: 5px;
	flex-shrink: 0;
}

.header-content {
	flex: 1;
	margin-left: 10px;
	display: flex;
	align-items: center;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	min-width: 0; /* 确保flex子项可以收缩 */
}

.header-title {
	font-size: 18px;
	font-weight: bold;
	color: var(--text-color);
	overflow: hidden;
	text-overflow: ellipsis;
	flex-shrink: 1; /* 允许标题收缩 */
	min-width: 0; /* 确保文本可以收缩 */
}

.header-count {
	font-size: 14px;
	color: #999;
	margin-left: 5px;
	flex-shrink: 0;
}

.header-right {
	display: flex;
	align-items: center;
	flex-shrink: 0;
	margin-left: 10px; /* 确保与中间内容有间距 */
}

.task-content {
	flex: 1;
	padding: 10px 8px; /* 进一步减少内边距 */
	width: 100%;
	box-sizing: border-box;
	-webkit-overflow-scrolling: touch; /* 增强iOS滚动体验 */
	overflow-x: hidden; /* 防止水平溢出 */
}

.task-sections-container {
	position: relative;
	width: 100%;
	display: flex;
	flex-direction: column;
	gap: 8px; /* 使用gap属性控制间距 */
}

.task-section {
	width: 100%;
	background-color: var(--card-background-color, #fff);
	border-radius: 8px; /* 减小圆角 */
	padding: 6px; /* 减少内边距 */
	box-sizing: border-box; /* 确保padding包含在宽度内 */
	box-shadow: none; /* 移除阴影 */
	position: relative;
	margin-bottom: 0; /* 移除底部间距，使用gap控制 */
}

.task-section-header {
	margin-bottom: 4px; /* 减少底部间距 */
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 4px 2px; /* 调整内边距 */
	border-bottom: none; /* 移除底部边框 */
	flex-wrap: wrap; /* 允许在必要时换行 */
	cursor: pointer; /* 添加指针样式表示可点击 */
}

.task-section-left {
	display: flex;
	align-items: center;
	flex: 1;
	min-width: 0;
}

.task-section-indicator {
	width: 3px;
	height: 16px;
	border-radius: 1.5px;
	margin-right: 8px;
	flex-shrink: 0;
}

.todo-indicator {
	background-color: #909399;
}

.doing-indicator {
	background-color: #1890ff;
}

.done-indicator {
	background-color: #42b983;
}

.task-section-title {
	font-size: 15px;
	font-weight: 600;
	color: var(--text-color);
	white-space: nowrap; /* 防止标题换行 */
	overflow: hidden; /* 隐藏溢出内容 */
	text-overflow: ellipsis; /* 显示省略号 */
	max-width: 70%; /* 限制最大宽度 */
}

.task-section-count {
	font-size: 12px;
	color: #999;
	margin-left: 5px;
	background-color: rgba(0, 0, 0, 0.05);
	padding: 1px 6px;
	border-radius: 10px;
	min-width: 20px; /* 减小最小宽度 */
	text-align: center;
}

.task-section-toggle {
	padding: 4px;
	flex-shrink: 0;
}

.task-list-wrapper {
	overflow: hidden;
	max-height: 500px; /* 减小最大高度，避免过长的动画时间 */
	opacity: 1;
	transition: max-height 0.25s ease-out, opacity 0.15s ease-out;
	position: relative;
	
	&.collapsed {
		max-height: 0;
		opacity: 0;
		transition: max-height 0.2s ease-in, opacity 0.1s ease-in;
	}
}

.task-list {
	width: 100%;
	overflow-x: hidden; /* 防止水平溢出 */
	padding-top: 2px;
}

.task-item-wrapper {
	margin-bottom: 6px; /* 减少任务项间距 */
	transition: all 0.3s ease;
	transform: translateZ(0); /* 启用硬件加速 */
	width: 100%;
	box-sizing: border-box;
	overflow: hidden; /* 防止内容溢出 */
	
	&:last-child {
		margin-bottom: 0;
	}
	
	&:active {
		transform: scale(0.98);
		opacity: 0.9;
	}
}

.task-empty {
	margin-top: 50rpx;
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	flex: 1;
	padding: 30rpx;
}

.empty-container {
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 100%;
	background-color: var(--card-background-color, #fff);
	border-radius: 12px;
	padding: 40rpx;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-image {
	width: 320rpx;
	height: 240rpx;
	margin-bottom: 40rpx;
	opacity: 0.8;
}

.empty-text {
	font-size: 32rpx;
	color: #666;
	font-weight: 500;
	margin-bottom: 10rpx;
}

.empty-tips {
	font-size: 28rpx;
	color: #999;
	margin-top: 20rpx;
	line-height: 1.5;
	background-color: rgba(0, 0, 0, 0.03);
	padding: 15rpx 30rpx;
	border-radius: 30rpx;
}

.add-button {
	position: fixed;
	right: 20px;
	bottom: 30px;
	width: 50px;
	height: 50px;
	border-radius: 25px;
	background-color: #4285f4;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2px 10px rgba(66, 133, 244, 0.2);
	z-index: 10;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.9);
		box-shadow: 0 1px 5px rgba(66, 133, 244, 0.3);
	}
}

@media screen and (max-width: 375px) {
	.task-content {
		padding: 6px; /* 减少内容区内边距 */
	}
	
	.task-sections-container {
		gap: 6px; /* 小屏幕设备减少间距 */
	}
	
	.task-section {
		padding: 4px; /* 进一步减少内边距 */
	}
	
	.task-section-header {
		margin-bottom: 3px; /* 减少底部间距 */
		padding: 3px 2px; /* 调整内边距 */
	}
	
	.task-section-indicator {
		height: 14px; /* 减小指示条高度 */
	}
	
	.task-section-title {
		max-width: 60%;
		font-size: 14px;
	}
	
	.task-section-count {
		padding: 0px 5px;
		font-size: 11px;
		min-width: 18px; /* 减小最小宽度 */
	}
	
	.header-title {
		font-size: 16px; /* 减小标题字体 */
	}
}
</style> 